package code.coolbaby.sms.service;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.lang.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import code.coolbaby.sms.entity.MessagesToSend;

import com.jasson.im.api.APIClient;

/**
 * MAS短信发送服务类.
 * 
 * 此处只做简单的发送演示,可根据业务需求自行扩展实现接收等功能
 * 
 * @author Kanine
 */
@Service
public class MobileAgentService {

	protected APIClient client;// MAS客户端

	/**
	 * 每条短信最多字符数;MAS规范中,MT短信最大支持2000个汉字,
	 * PDU短信最大支持140个汉字，超出部分则截断,但其拆分性能不佳,
	 * 故此处按每条短信70个字符的长度作分割
	 */
	protected static final int MAX_CHARACTERS = 70;
	
	/**
	 * MAS规范中短信定时发送的时间格式
	 */
	protected static final FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH-mm-ss");

	protected Logger logger = LoggerFactory.getLogger("code.coolbaby");
	
	/**
	 * 在bean创建后初始化APIClient等.
	 */
	@PostConstruct
	protected void postConstruct() {
		Properties prop = new Properties();
		try {
			prop.loadFromXML(getClass().getResourceAsStream("/mas.xml"));
		} catch (IOException ioe) {
			logger.error(ioe.getMessage());
			return;// 配置文件读取错误则立即返回
		}
		String description = "";
		this.client = new APIClient();
		int statusCode = client.init(prop.getProperty("mas.dbIp"), prop.getProperty("mas.dbUser"), prop.getProperty("mas.dbPwd"), prop.getProperty("mas.apiCode"), prop.getProperty("mas.dbName"));
		switch (statusCode) {
			case APIClient.IMAPI_SUCC:
				description = "初始化成功";
				break;
			case APIClient.IMAPI_CONN_ERR:
				description = "连接失败";
				break;
			case APIClient.IMAPI_API_ERR:
				description = "apiID不存在";
				break;
		}
		logger.info("MAS客户端{}!", description);
	}

	/**
	 * 发送短信息.
	 * 
	 * @param numbers - 手机号码列表,以,分隔.
	 * @param message - 待发送的短信息内容.
	 * @param message - 定时短信的发送时间.
	 */
	public void sendMsg(String numbers, String message,String sendTime) {
		int statusCode = 0;
		String[] mobiles = numbers.split(",");

		StringBuffer sb = new StringBuffer(message);
		int count = sb.length() / MAX_CHARACTERS;
		for (int i = 0; i < count; i++)
			sb.insert((i + 1) * MAX_CHARACTERS + i, ',');
		String[] content = sb.toString().split(",");//分拆短信息

		for (int k = 0; k < content.length; k++) {
			statusCode = client.sendSM(mobiles, content[k], sendTime, 0, 0);
			logger.info("发送状态：{}", dealWithResponse(statusCode, null));
		}
	}
	
	/**
	 * 发送短信息.
	 */
	public void sendMsg(MessagesToSend msg) {
		String sendTime = null;
		if (msg.getSendTime() != null)
			sendTime = fdf.format(msg.getSendTime());
		sendMsg(msg.getMobiles(), msg.getContent(), sendTime);
	}
	
	/**
	 * 发送短信息.
	 */
	public void sendMsg(List<MessagesToSend> msgs) {
		if (msgs != null && msgs.size() > 0)
			for (MessagesToSend msg : msgs)
				this.sendMsg(msg);
	}

	/**
	 * 根据MAS发送短信后的返回值作相应的业务处理.
	 * 
	 * @param statusCode - MAS返回值.
	 * @param messageId - 已发送的短信息主键.
	 */
	protected String dealWithResponse(int statusCode, Long messageId) {
		String description;
		switch (statusCode) {
			case APIClient.IMAPI_SUCC:
				description = "发送成功";
				//do sth here
				break;
			case APIClient.IMAPI_INIT_ERR:
				description = "未初始化";
				break;
			case APIClient.IMAPI_CONN_ERR:
				description = "数据库连接失败";
				break;
			case APIClient.IMAPI_DATA_ERR:
				description = "参数错误";
				break;
			case APIClient.IMAPI_DATA_TOOLONG:
				description = "消息内容太长";
				break;
			case APIClient.IMAPI_INS_ERR:
				description = "数据库插入错误";
				break;
			default:
				description = "出现其他错误";
		}
		return description;
	}

	/**
	 * 在bean销毁前释放所占有的资源.
	 */
	@PreDestroy
	protected void preDestroy() {
		this.client.release();
	}
}
